package com.wing.device.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.device.model.entity.DeviceBrand;
import com.wing.device.model.entity.DeviceCategory;
import com.wing.device.model.response.DeviceModelVO;
import com.wing.device.service.DeviceBrandService;
import com.wing.dict.model.entity.DictLabel;
import com.wing.product.model.response.ProductTypeVO;
import com.wing.product.service.ProductTypeService;
import com.wing.purchase.model.entity.SupplierInfo;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.CompanyInfoVO;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.device.model.entity.DeviceModel;
import com.wing.device.model.request.DeviceModelForm;
import com.wing.device.service.DeviceModelService;
import com.wing.web.excel.DeviceExcelIn;
import com.wing.web.excel.DeviceModelExcelIn;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-设备型号管理", tags = "#/device/deviceModel")
@RestController("deviceModelController")
@RequestMapping("device/admin/deviceModel")
@Slf4j
public class DeviceModelController {

    @Autowired
    private DeviceModelService deviceModelService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private DeviceBrandService deviceBrandService;



    @ApiOperation(value = "查询所有设备型号", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<DeviceModelVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,String name
            ,String notInListIds
    ){

        Page<DeviceModelVO> pg = new Page<>(page, limit);
        Map<String,Object> paramMap=new HashMap();
        paramMap.put("name",name);
        if (StringUtils.isNotBlank(notInListIds)) {
            String[] lists = notInListIds.split(",");
            paramMap.put("notInListIds", lists);
        }
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            paramMap.put("sort",sort);
            paramMap.put("order",order);
        }
//        QueryWrapper<DeviceModel> queryWrapper = new QueryWrapper<>();
//
//        //排序
//        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
//            if (StringUtils.equals("asc", order)) {
//                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
//            } else {
//                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
//            }
//        }
//
//        //搜索
//        if (StringUtils.isNotBlank(name)) {
//            queryWrapper.like("name", name);
//        }
        Page<DeviceModelVO> list = deviceModelService.pageList4app(pg, paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    /**
     * 查询所有型号
     * @return
     */
    @GetMapping("/getAllModel")
    public JsonResult getAllModel(){

        return JsonResult.success(deviceModelService.list());
    }



    @ApiOperation(value = "添加设备型号", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime,remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(DeviceModelForm.Add.class) DeviceModelForm deviceModelForm) {

        if (deviceModelService.add(deviceModelForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改设备型号", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(DeviceModelForm.Update.class) DeviceModelForm deviceModelForm) {

        DeviceModel deviceModel = deviceModelService.getById(deviceModelForm.getId());
        if(deviceModel == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(DeviceModel.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(deviceModelForm, deviceModel, copyOptions);
        if (deviceModelService.updateById(deviceModel)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除设备型号", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deviceModelId", value = "设备型号id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long deviceModelId) {

        if (deviceModelService.removeById(deviceModelId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    //批量删除
    @ApiOperation(value = "批量删除设备型号", notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "设备型号id", required = true, dataType = "String", paramType = "query")
    })
    //@PostMapping( )
    @DeleteMapping("/delBatch")
    public JsonResult delete(String ids) {

        if (StringUtils.isNotBlank(ids)){
            List<Long> idList=new ArrayList<>();
            String[] idArray=ids.split(",");
            for (int i=0;i<idArray.length;i++){
                idList.add(Long.valueOf(idArray[i]));
            }
            if(deviceModelService.remove(new QueryWrapper<DeviceModel>().in("id",idList))){
                return JsonResult.success("删除成功");
            }
        }else{
            return JsonResult.fail("请选择数量");
        }
        return JsonResult.fail("删除失败");
    }


    /**
     * 下载设备数据录入excel模板
     */
    @ApiOperation(value = "下载设备数据录入excel模板")
    @GetMapping("/deviceTemplate")
    public void deviceTemplate(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"设备类型(*)","设备品牌(*)","设备型号名称(*)","设备型号编码(*)","设备编码头","厂家名称","厂家联系人",
                "厂家网站","备注说明"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        //设备类型
        StringBuffer tempStr = new StringBuffer();
        Map<String, Object> productTypeParams = new HashMap<>();
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (org.apache.commons.lang.StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        productTypeParams.put("databaseUser", databaseUser);
        List<ProductTypeVO> deviceTypeList = productTypeService.list4app(productTypeParams);
        if(CollectionUtil.isNotEmpty(deviceTypeList)){
            for (ProductTypeVO deviceType : deviceTypeList) {
                tempStr.append(deviceType.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("0");
        }
        //设备品牌
        List<DeviceBrand> deviceBrandList = deviceBrandService.list();
        if(CollectionUtil.isNotEmpty(deviceBrandList)){
            for (DeviceBrand deviceBrand : deviceBrandList) {
                tempStr.append(deviceBrand.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("1");
        }
        DownExcelUtil.createExcelTemplate(response, request, "设备型号导入模板", Arrays.asList(headerArr), downData, indexArr);
    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<DeviceModelExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<DeviceModelExcelIn> list = reader.read(is, DeviceModelExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            deviceModelService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }
}
